package com.fy56.platform.logistics.restful.api.utils.redis;

import com.fy56.platform.logistics.restful.api.utils.ConstansUtils;
import com.fy56.platform.logistics.restful.api.utils.StringToConversionUtil;
import com.fy56.platform.logistics.restful.api.utils.weChat.WeChatAppletUtil;
import com.fy56.platform.logistics.restful.api.utils.weChat.WeChatOfficialAccountUtil;
import com.fy56.platform.logistics.service.common.IRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Redis缓存业务工具类
 */
@Component
public class RedisBusinessUtils {

    @Autowired
    private IRedisService iRedisService;

    /*----------------------------------------------------------------------------------------------------*/

    /**
     * [获取]微信-accessToken
     * @param appId
     * @param appSecret
     * @return
     */
    public String getWxAppletAccessToken(String appId, String appSecret) {
        String accessToken = "";

        //[生成]微信_accessToken的key
        String wechat_accesstoken_key= RedisKeyFactoryUtils.KeyGenerator.WECHAT_ACCESSTOKEN.getKey(appId);
        if(iRedisService.hasKey(wechat_accesstoken_key)){
            accessToken = iRedisService.get(wechat_accesstoken_key).toString();
        }else{
            try {
                // 获取微信小程序-accessToken
                accessToken = WeChatAppletUtil.getAccessToken(appId, appSecret);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(StringToConversionUtil.isNotNull(accessToken)){
                //存储到redis
                iRedisService.set(wechat_accesstoken_key, accessToken, ConstansUtils.SYS_CONSTANS.ACCESSTOKEN_PUD_TIMENUM*60);
            }
        }

        return accessToken;
    }

    /*----------------------------------------------------------------------------------------------------*/

    /**
     * [获取]微信JS-SDK-签名凭证(jsapi_ticket)
     * @param accessToken
     * @return
     */
    public String getWxJsApiTicket(String accessToken) {
        String jsapiTicket = "";

        //[生成]微信JS-SDK-签名凭证_jsapiTicket的key
        String wechat_jsapiTicket_key= RedisKeyFactoryUtils.KeyGenerator.WECHAT_JSAPITICKET.getKey(accessToken);
        if(iRedisService.hasKey(wechat_jsapiTicket_key)){
            jsapiTicket = iRedisService.get(wechat_jsapiTicket_key).toString();
        }else{
            try {
                // 获取微信JS-SDK-签名凭证(jsapi_ticket)
                jsapiTicket = WeChatOfficialAccountUtil.getJsApiTicket(accessToken);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(StringToConversionUtil.isNotNull(jsapiTicket)){
                //存储到redis
                iRedisService.set(wechat_jsapiTicket_key, jsapiTicket, ConstansUtils.SYS_CONSTANS.JSAPITICKET_PUD_TIMENUM*60);
            }
        }

        return jsapiTicket;
    }
}
